#!coding:utf8
from cvirt.tasks import *
from cvirt.manager.models import Instance, Snapshot
from cvirt.cnode.vm import power_state


class ScheduleDispatcher(object):
    def __init__(self, kwargs):
        self.kwargs = kwargs

    def getVm(self):
        inst_id = self.kwargs.get('instid')
        instance = Instance.objects.filter(id=inst_id)
        if not instance:
            raise Exception('no vm exists')
        return instance[0]

    def getSnapshot(self):
        snap_id = self.kwargs.get('snapshotid')
        snap = Snapshot.objects.filter(id=snap_id)
        if not snap:
            raise Exception('snapshot not exists')
        return snap[0]

    def create_db_snapshot(self, vm):
        snap = Snapshot.objects.create(name=self.kwargs['snapshotname'], description=u"计划任务创建",
                                       instance=vm, uuid=uuid.uuid4().hex,
                                       status=power_state.name(power_state.BUILDING))
        return snap

    def startvm(self):
        vm = self.getVm()
        start_vm(vm)

    def shutdownvm(self):
        vm = self.getVm()
        shutdown_vm(vm)

    def rebootvm(self):
        vm = self.getVm()
        reboot_vm(vm)

    def deletevm(self):
        vm = self.getVm()
        delete_vm(vm)

    def snapshotvm(self):
        vm = self.getVm()
        snap = self.create_db_snapshot(vm)
        snapshot_vm(vm, snap)

    def snapshotrestore(self):
        vm = self.getVm()
        snap = self.getSnapshot()
        snapshot_restore(vm, snap)
